<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { bgColors, isPhone } from '@/plugins/util.js'
import { setUserExtInfoApi } from '@/plugins/http/api/user'
import { useToast } from '@/composition/useToast'


import draggable from "vuedraggable";
import { generateUUID, copyJSON, isNotEmpty, isEmpty, uploadFile, go2Router, go2Link, saveUser2Db } from '@/plugins/util.js'

import { useConfirm } from '@/composition/useConfirm'

const { showConfirm } = useConfirm();

// import { guides } from './homeData.js'


import { useUser } from '@/composition/useUser'
import { computed } from 'vue';

const { loginModel, user, login, loggedIn, logout } = useUser();
const { successToast, errorToast, infoToast } = useToast();


// const router = useRouter();

// let guides = computed(() => user.value.extInfo.guide);
const guide = ref(copyJSON(user.value.extInfo.guide));


/*
draggable 对CSS样式没有什么要求万物皆可拖拽
:list="state.list"         //需要绑定的数组
ghost-class="ghost"        //被替换元素的样式
chosen-class="chosenClass" //选中元素的样式
animation="300"            //动画效果
@start="onStart"           //拖拽开始的事件
@end="onEnd"               //拖拽结束的事件
*/

const guideSortChange = () => {
    for (let index = 0; index < guide.value.urls.length; index++) {
        const item = guide.value.urls[index];
        item.sort = index + 1;
        item.uuid = generateUUID();
    }
    saveGuide2Db();
};

const show = ref(false);

const guideItem = ref({
    uuid: '',
    name: '',
    icon: '',
    url: '',
    urlZ: '',
    desc: '',
});

// saveUser2Db
const saveGuide2Db = () => {
    user.value.extInfo.guide = guide.value;
    saveUser2Db()
}


const guideSubmit = () => {
    if (isNotEmpty(guideItem.value.uuid)) {
        // 修改
        editGuide();
    } else {
        // 新增
        addGuide();
    }

}

// const upIcon = async () => {
//     if (!loggedIn.value) {
//         return;
//     }
//     const icon = guideItem.value.icon;
//     if (isNotEmpty(icon) && icon.startsWith('data:')) {
//         // 上传到服务器，并且替换为url
//         if (fileInfo != null) {
//             const iconUrl = await uploadFile(fileInfo.file);
//             console.log('iconUrl:', iconUrl);
//             guideItem.value.icon = iconUrl;
//             fileInfo = null;
//         }
//     }
// }

const addGuide = async () => {
    // guideItem.value.sort = guides.value.length + 1;
    // await upIcon();
    if (guideItem.value.icon == '') {
        guideItem.value.icon = 'https://ui-avatars.com/api/?&rounded=true&font-size=0.33&name=' + guideItem.value.name
    }
    guideItem.value.uuid = generateUUID();
    guide.value.urls.push(copyJSON(guideItem.value));
    show.value = false;
    saveGuide2Db();
}

const deleteGuide = (uuid) => {
    guideItem.value.uuid = uuid
    showConfirm({ content: '确认删除吗？' }).then(() => {
        delGuide();
    }).catch(() => { })
}

const delGuide = () => {
    guide.value.urls = guide.value.urls.filter(item => item.uuid != guideItem.value.uuid);
    saveGuide2Db();
}

const showAddGuide = () => {
    show.value = true;
    guideItem.value = {};
}

const showEditGuide = (guide) => {
    // user.value.extInfo.guides = guides.value;
    // saveGuide2Db();
    // debugger;
    show.value = true;
    guideItem.value = copyJSON(guide);
}

const editGuide = async () => {
    // await upIcon();
    // debugger;
    guide.value.urls.forEach(item => {
        if (item.uuid == guideItem.value.uuid) {
            item.name = guideItem.value.name;
            item.url = guideItem.value.url;
            item.icon = guideItem.value.icon;
            return false;
        }
    });
    show.value = false;
    saveGuide2Db();
}


onMounted(() => {
    guide.value.urls.forEach(item => {
        setDefaultIcon(item)
        const name = item.name;
        const icon = item.icon;
        if (isNotEmpty(name) && isEmpty(icon)) {
            item.icon = 'https://ui-avatars.com/api/?&rounded=true&font-size=0.33&name=' + name;
        }
    })
})


const setDefaultIcon = (guide) => {
    const name = guide.name;
    const icon = guide.icon;
    if (isNotEmpty(name) && isEmpty(icon)) {
        guide.icon = 'https://ui-avatars.com/api/?&rounded=true&font-size=0.33&name=' + name;
    }
}

const uploadEle = ref()


const showTitleClick = (showTitle) => {
    guide.value.showTitle = showTitle
    saveGuide2Db()
}

const openUrlTypeClick = (openUrlType) => {
    guide.value.openUrlType = openUrlType
    saveGuide2Db()
}



</script>

<template>
    <div class="h-container">
        <div class="m-5">
            <header class="border-l-8 border-green-500 py-3 pl-4 bg-green-200 rounded italic tracking-widest">
                <span class="text-indigo-500 cursor-pointer" @click="go2Router('home')">主页</span>
                <span class="mx-2">/</span>
                <span>导航设置</span>
            </header>

            <section class="mt-4">

                <div class="w-full py-3 pl-4 bg-green-200 text-sm rounded text-green-900 tracking-widest mb-2 flex">
                    <div class="mr-2">导航标题</div>
                    <div class="flex">
                        <div class="flex justify-center items-center">
                            <input @click="showTitleClick(true)" :checked="guide.showTitle" type="radio"
                                name="showTitleCheck" class="mr-2" id="showTitleCheckTrue" /><label for="showTitleCheckTrue"
                                class="cursor-pointer">显示</label>
                        </div>
                        <div class="flex justify-center items-center cursor-pointer ml-2">
                            <input @click="showTitleClick(false)" :checked="!guide.showTitle" type="radio"
                                name="showTitleCheck" class="mr-2" id="showTitleCheckFalse" /><label
                                for="showTitleCheckFalse" class="cursor-pointer">隐藏</label>
                        </div>
                    </div>
                </div>

                <div class="w-full py-3 pl-4 bg-green-200 text-sm rounded text-green-900 tracking-widest mb-2 flex">
                    <div class="mr-2">导航打开方式</div>
                    <div class="flex">
                        <div class="flex justify-center items-center">
                            <input @click="openUrlTypeClick('_blank')" :checked="guide.openUrlType == '_blank'" type="radio"
                                name="openUrlTypeCheck" class="mr-2" id="openUrlTypeCheckTrue" /><label for="openUrlTypeCheckTrue"
                                class="cursor-pointer">新标签页</label>
                        </div>
                        <div class="flex justify-center items-center cursor-pointer ml-2">
                            <input @click="openUrlTypeClick('_self')" :checked="guide.openUrlType == '_self'" type="radio"
                                name="openUrlTypeCheck" class="mr-2" id="openUrlTypeCheckFalse" /><label
                                for="openUrlTypeCheckFalse" class="cursor-pointer">当前页</label>
                        </div>
                    </div>
                </div>

                <draggable class="grid grid-cols-1 gap-5 " v-model="guide.urls" @change="guideSortChange" item-key="guides"
                    filter=".opertion">
                    <template #item="{ element }">
                        <div class="shadow-md bg-gray-300 cursor-pointer rounded p-1  flex justify-between">
                            <div class="flex justify-start">
                                <div class="w-12 h-12 bg-contain bg-center bg-no-repeat flex items-end cursor-pointer rounded relative"
                                    :style="{
                                        backgroundImage: 'url(' + element.icon + ')'
                                    }">
                                </div>
                                <div class="p-2 flex items-center" :title="element.name" style="max-width: 40vw;">
                                    <span class="text-black text-sm truncate">{{ element.name }}</span>
                                </div>
                            </div>
                            <div class="opertion h-12  flex justify-end items-center pr-2 space-x-3">
                                <button type="button" @click="showEditGuide(element)" class="btn btn-primary">
                                    编辑
                                </button>
                                <button type="button" @click="deleteGuide(element.uuid)" class="btn btn-warning">
                                    删除
                                </button>
                            </div>
                        </div>
                    </template>

                    <template #footer>
                        <!-- <div class="w-full h-36 bg-cover bg-center bg-no-repeat flex items-end cursor-pointer rounded relative"
                            @click="showAddGuide()">
                            <div class="text-white w-full p-2 text-sm bg-black bg-opacity-20 truncate">
                                +
                            </div>
                        </div> -->
                        <div class="shadow-md bg-gray-300 h-12 cursor-pointer rounded p-1 flex justify-center items-center"
                            @click="showAddGuide()">
                            <span class="text-black text-lg">+</span>
                        </div>
                    </template>

                </draggable>

                <h-pop :show="show" :style-set="{ top: '10%', maxWidth: '800px' }" @close="show = false">
                    <template #header>
                        <div>编辑导航</div>
                    </template>
                    <template #main>
                        <div class="grid grid-cols-1 md:gap-y-5">
                            <h-input v-model="guideItem.url" label="导航链接：">
                                <!-- <template #right>
                                    <button type="button" class="btn btn-primary w-36"
                                        @click="setDefaultIcon(guideItem)">抓取信息</button>
                                </template> -->
                            </h-input>
                            <h-input v-model="guideItem.name" label="导航名称：" class="w-full"
                                @blur="setDefaultIcon(guideItem)"></h-input>
                            <h-input v-model="guideItem.icon" label="导航图标：">
                                <template #right>
                                    <div class="btn btn-primary w-20 py-2.5 flex items-center justify-center text-lg cursor-pointer"
                                        @click="uploadEle.click()">
                                        <i class="fas fa-cloud-upload-alt"></i>
                                    </div>
                                    <h-upload ref="uploadEle" @upLoadSuccess="(url) => { guideItem.icon = url }"></h-upload>
                                </template>
                            </h-input>
                            <div class="flex justify-center items-center mt-2 md:mt-0">
                                <img v-show="isNotEmpty(guideItem.icon)" :src="guideItem.icon"
                                    class="h-20 cursor-pointer rounded" @click="go2Link(editIcon)">
                            </div>
                        </div>
                    </template>
                    <template #footer>
                        <div class="h-12 w-full flex justify-end items-center pr-2 space-x-4">
                            <button type="button" @click="show = false" class="btn btn-secondary">
                                关闭
                            </button>
                            <button type="button" @click="guideSubmit()" class="btn btn-primary">
                                保存
                            </button>
                        </div>
                    </template>
                </h-pop>
            </section>
        </div>
    </div>




    <!-- <van-action-sheet v-model:show="show" title="导航">
        <van-form @submit="guideSubmit">
            <van-cell-group inset>
                <van-field v-model="guideItem.name" name="name" label="名称" placeholder="名称"
                    :rules="[{ required: true, message: '请填写名称' }]" @blur="getDefaultIcon()" />
                <van-field v-model="guideItem.url" name="url" label="地址" placeholder="地址"
                    :rules="[{ required: true, message: '请填写地址' }]" />
                <van-field name="uploader" label="图标">
                    <template #input>
                        <van-uploader v-model="fileList" :after-read="afterRead" reupload max-count="1" @delete="delImg" />
                    </template>
                </van-field>
            </van-cell-group>
            <div style="padding: 0 2px;">
                <van-button block type="primary" native-type="submit">确定</van-button>
            </div>
        </van-form>
    </van-action-sheet> -->
</template>

<style scoped>
/* :deep(.van-grid-item) {
  width: 100%;
} */
</style>
